//
//  KSImagePicker.swift
//  Slaughter
//
//  Created by Ken on 2020/10/9.
//  Copyright © 2020 zwb. All rights reserved.
//
//  图片选择工具
import UIKit
import TZImagePickerController
import Photos
import AVFoundation
import MobileCoreServices
enum PictureType {
     case takePicture,// 拍照
          cameraContinuous,// 连续拍照
          albumPicture,// 相册图片
         allfile,// 全部文件
         pdfFile,//pdf文件
          albumVideo,//相册视频
          videoRecording // 录视频
    
    //     全部文件默认也支持pdf图片   视频默认也支持图片
    
 }

enum CameraAcType {
    case common,continueous  // 普通拍照，连续拍照
}
 
class KSImagePicker:NSObject,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate  {
  
    static let shared = KSImagePicker()
    var cameraAction:((UIImage)->())? // 拍照事件返回
     var ksPhotoAction:(([UIImage],[PHAsset])->())?
    var videoAction:((PHAsset?,URL?,UIImage)->())?
    
    var picType:[PictureType] = [.albumPicture]
    var cameraAcType:CameraAcType!
    fileprivate lazy var photosPickerC = UIImagePickerController()
    fileprivate lazy var vedioPickerC = UIImagePickerController()

    // 支持图片和拍照  支持裁剪，因为没法实现配置，所以另起一个先写死
    func showOnly4Crop(cameraAction:((UIImage)->())? = nil,photoAction:(([UIImage],[PHAsset])->())? = nil)  {
        self.ksPhotoAction = photoAction
        let imagePickerVc = TZImagePickerController.init(maxImagesCount:1, delegate: self)
        imagePickerVc!.allowTakePicture = true
        imagePickerVc!.allowPickingVideo = false
        imagePickerVc!.allowCrop = true
        imagePickerVc!.circleCropRadius = Int(KSGlobal.screenW / 2 - 10)
        imagePickerVc!.needCircleCrop = true
        if let topVC = getTopVC() {
            topVC.present_FullScreen(to: imagePickerVc!)
        }
    }
    
    
    func config(picType:[PictureType],cameraAction:((UIImage)->())? = nil,photpMaxImagesCount:Int = 1,photoAction:(([UIImage],[PHAsset])->())? = nil,videoAction:((PHAsset?,URL?,UIImage)->())? = nil,fileAction:(()->())? = nil) -> UIAlertController {
        
        self.picType = picType
   
        self.photosPickerC.sourceType = UIImagePickerController.SourceType.camera
        self.photosPickerC.delegate = self
        
        let alertSheet = UIAlertController(title: "选择", message: "", preferredStyle: UIAlertController.Style.actionSheet)
        let cancelAc = UIAlertAction(title: "取消", style:  .cancel, handler: nil)
        
        let cameraAc = UIAlertAction(title: "拍照片", style:  .default, handler:{
            action in
            self.cameraAcType = .common
            self.cameraAction = cameraAction
            if let topVC = getTopVC() {
                topVC.present(self.photosPickerC, animated: true, completion: {
                    self.photosPickerC.delegate = self
                })
            }
          
        })
        
        let videoAc = UIAlertAction(title: "录视频", style:  .default, handler:{
            action in
            self.videoAction = videoAction
            self.vedioPickerC.sourceType = UIImagePickerController.SourceType.camera
           
            self.vedioPickerC.mediaTypes = [kUTTypeMovie as String]
            self.vedioPickerC.cameraCaptureMode  = .video
            self.vedioPickerC.cameraDevice = .rear // 或 .rear 对于后置摄像头
            self.vedioPickerC.videoQuality = .typeMedium
            self.vedioPickerC.delegate = self
            if let topVC = getTopVC() {
                topVC.present(self.vedioPickerC, animated: true) {
                    
                }
            }
          
        })
        
     
        
        let cameraContinueAc = UIAlertAction(title: "连续拍照", style:  .default, handler:{
            action in
            self.cameraAcType = .continueous
            self.cameraAction = cameraAction
            if let topVC = getTopVC() {
                topVC.present(self.photosPickerC, animated: true, completion: {
                    self.photosPickerC.delegate = self
                })
            }
          
        })
        let photoAc = UIAlertAction(title: "从相册选择", style: .default, handler: {
            action in
            self.ksPhotoAction = photoAction
            self.videoAction = videoAction
            let imagePickerVc = TZImagePickerController.init(maxImagesCount:photpMaxImagesCount, delegate: self)
            imagePickerVc!.allowTakePicture = false
            
            
            imagePickerVc!.allowPickingVideo = false
            imagePickerVc!.allowTakeVideo = false
            
            imagePickerVc!.allowPickingImage = false
            imagePickerVc!.allowPickingOriginalPhoto = false
          
            
            
            if picType.contains(.albumPicture) {
                imagePickerVc!.allowPickingImage = true
                imagePickerVc!.allowPickingOriginalPhoto = true
            }
            if picType.contains(.albumVideo) {
                imagePickerVc!.allowPickingVideo = true
                imagePickerVc!.allowPickingMultipleVideo = true
//                imagePickerVc!.allowTakeVideo = true
             }
 
            if let topVC = getTopVC() {
                topVC.present_FullScreen(to: imagePickerVc!)
            }
             
        })
        let fileAc = UIAlertAction(title: "选取文件", style: .default, handler: {
            action in
            
            if let clo = fileAction {
                clo()
            }
          
        })
        
        alertSheet.addAction(cancelAc)
        if picType.contains(.takePicture) {
            alertSheet.addAction(cameraAc)
         }
        if picType.contains(.cameraContinuous) {
            alertSheet.addAction(cameraContinueAc)
         }
        if picType.contains(.videoRecording) {
            alertSheet.addAction(videoAc)
        }
         if picType.contains(.albumPicture) || picType.contains(.albumVideo) {
             alertSheet.addAction(photoAc)
         }
        if picType.contains(.allfile) || picType.contains(.pdfFile) {
            alertSheet.addAction(fileAc)
        }
      return alertSheet
       
    }
 
    // MARK: - 拍照后回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        
        
        if picker.sourceType == .camera
        {
            if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
 
                if let  clo  =  self.cameraAction {
                    clo(image)
                }
                 //此处先保存至相册
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            }
        }
        
        
        if let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
           
     
            let coverImg = getCoverImage(from: videoURL)
            if let clo = self.videoAction {
                clo(nil,videoURL,coverImg!)
            }
        }
   
     
        if self.cameraAcType == .continueous {
            UIView.animate(withDuration: 0.001) {
                picker.dismiss(animated: false, completion: nil)
            } completion: { _ in
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
                    if let topVC = getTopVC() {
                        topVC.present(self.photosPickerC, animated: true, completion: {
                            self.photosPickerC.delegate = self
                        })
                    }
                }
            }
        } else {
            picker.dismiss(animated: true, completion: nil)
        }
        
        
         
    }
 
    // MARK: - 选择图片后回调
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
     
        let asset = assets as! [PHAsset]
         if let  clo  =  self.ksPhotoAction {
            clo(photos,asset)
        }
      }
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: PHAsset!) {
        
        if let clo = self.videoAction {
            clo(asset,nil,coverImage)
        }
        
    }
    
  func getCoverImage(from videoURL: URL) -> UIImage? {
      let asset = AVAsset(url: videoURL)
      let imageGenerator = AVAssetImageGenerator(asset: asset)
      imageGenerator.appliesPreferredTrackTransform = true
        
      let time = CMTimeMake(value: 0, timescale: 1) // 通常选择视频的第一帧作为封面
      do {
          let imageRef = try imageGenerator.copyCGImage(at: time, actualTime: nil)
          return UIImage(cgImage: imageRef)
      } catch {
          print("Error generating image from video")
          return nil
      }
  }
}

// MARK: - 查找顶层控制器、
// 获取顶层控制器 根据window
func getTopVC() -> (UIViewController?) {
    var window = getKeyWindow()
    //是否为当前显示的window
    if window?.windowLevel != UIWindow.Level.normal {
        let windows = UIApplication.shared.windows
        for  windowTemp in windows{
            if windowTemp.windowLevel == UIWindow.Level.normal {
                window = windowTemp
                break
            }
        }
    }
    let vc = window?.rootViewController
    return getTopVC(withCurrentVC: vc)
}
///根据控制器获取 顶层控制器
func getTopVC(withCurrentVC VC :UIViewController?) -> UIViewController? {
    if VC == nil {
        print("🌶： 找不到顶层控制器")
        return nil
    }
    if let presentVC = VC?.presentedViewController {
        //modal出来的 控制器
        return getTopVC(withCurrentVC: presentVC)
    }else if let tabVC = VC as? UITabBarController {
        // tabBar 的跟控制器
        if let selectVC = tabVC.selectedViewController {
            return getTopVC(withCurrentVC: selectVC)
        }
        return nil
    } else if let naiVC = VC as? UINavigationController {
        // 控制器是 nav
        return getTopVC(withCurrentVC:naiVC.visibleViewController)
    } else {
        // 返回顶控制器
        return VC
    }
}
